import React, { Component, PropTypes } from 'react';
import Echarts from 'echarts';
import { connect } from 'dva'
import {
  Input,
  Button,
  Select,
  Form,
  Modal,
  Row,
  Col,
  Icon,
  Radio,
  message,
} from 'antd';
import Style from './home.less';
import NumberPlay from '../../util/numberPlay';
import $ from 'jquery';
import Service from "../../service";
const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
var picker;
var nameEl;
var first = []; /* 省，直辖市 */
var second = []; /* 市 */
var third = []; /* 镇 */

var selectedIndex = [0, 0, 0]; /* 默认选中的地区 */

var checked = [0, 0, 0]; /* 已选选项 */

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      province: '请选择',
      region: '',
      city: ''
    };
  }
  componentWillMount() {
    const token = localStorage.getItem('token');
    let self = this;
    // this.props.queryStatistics({ token: token });
    self.props.e_bikeInfo({
      params: {
        token: token,
      },
      func: function (result) {

      }
    })
    self.props.queryProvince({ pid: 0 });
    // this.props.getCompany({ token: token });
  }
  componentDidMount() {
    let info = this.props.kData;
    // console.log(this.props.Statistics)
    if (info) {
      if (info.province_id) {
        this.props.queryCity({ pid: info.province_id });
        this.setState({
          province: info.province_id,
          city: '',
          region: ''
        })
      }
      if (info.city_id) {
        this.props.queryRegion({ pid: info.city_id });
        this.setState({
          city: info.city_id,
          region: ''
        })
      }
      if (info.region_id) {
        this.setState({
          region: info.region_id
        })
      }
    }

    this.cityInit();
  }
  componentWillUnmount() {
    if (this.state.timer != null) {
      clearInterval(this.state.timer);

    }
  }

  returnFun = () => {
    this.context.router.push(`/1/app/kmy`);
  }
  handleChangeCity = (value) => {
    this.props.queryCity({ pid: value });
    this.setState({
      province: value,
      city: '请选择',
      region: '请选择'
    })
  }
  handleChangeRegion = (value) => {
    this.props.queryRegion({ pid: value });
    this.setState({
      city: value,
      region: '请选择'
    })
    // console.log(value);
  }
  handleChange = (value) => {
    this.setState({
      region: value
    })
    // console.log(value);
  }
  provice(pid, level, arr, type, ) {
    var self = this;
    $.ajax({
      type: "POST",
      url: `${Service.baseUrl}/tool/area`,
      data: { level: level, pid: pid },
      dataType: "json",
      async: false,
      success: function (data) {
        if (data.code == 200) {
          if (type == 1) {
            self.creatList(data.data, arr);
          } else if (type == 2) {
            if (data.data) {
              self.creatList(data.data, second);
              // 请求三级数据
              var pids = data.data[0].id;
              self.provice(pids, 3, third, 3);
            } else {
              second = [{ text: '', value: 0 }];
              third = [{ text: '', value: 0 }];
              checked[1] = 0;
              checked[2] = 0;
            }
          } else if (type == 3) {
            if (data.data) {
              self.creatList(data.data, third);
            } else {
              third = [{ text: '', value: 0 }];
              checked[2] = 0;
            }
          } else if (type == 4) {
            if (data.data) {
              self.creatList(data.data, third);
              picker.refillColumn(2, third);
              picker.scrollColumn(2, 0)
            } else {
              third = [{ text: '', value: 0 }];
              checked[2] = 0;
              picker.refillColumn(2, third);
              picker.scrollColumn(2, 0)
            }
          }

        }
      }
    });
  }
  cityInit = () => {
    var self = this;
    nameEl = document.getElementById('citybtn');
    self.provice(0, 1, first, 1);
    // self.provice(1, 1, second, 2);
    self.provice(2, 3, third, 3);
    // self.creatList(city, first);

    if (city[selectedIndex[0]].hasOwnProperty('sub')) {
      self.provice(1, 1, second, 2);
      // self.creatList(city[selectedIndex[0]].sub, second);
    } else {
      second = [{ text: '', value: 0 }];
    }

    // if (city[selectedIndex[0]].sub[selectedIndex[1]].hasOwnProperty('sub')) {
    //   self.provice(2, 3, third, 3);
    //   // self.creatList(city[selectedIndex[0]].sub[selectedIndex[1]].sub, third);
    // } else {
    //   third = [{ text: '', value: 0 }];
    // }

    picker = new Picker({
      data: [first, second, third],
      selectedIndex: selectedIndex,
      title: '地址选择'
    });


    picker.on('picker.select', function (selectedVal, selectedIndex) {
      // console.log(first)
      // console.log(first[selectedIndex[0]])
      var text1 = first[selectedIndex[0]].text;
      var text2 = second[selectedIndex[1]].text;
      var text3 = third[selectedIndex[2]] ? third[selectedIndex[2]].text : '';

      if (self.state.areaType == 1) {
        self.setState({
          province_id: first[selectedIndex[0]].value,
          city_id: second[selectedIndex[1]].value,
          region_id: third[selectedIndex[2]] ? third[selectedIndex[2]].value : '',
          provinceCity: text1 + text2 + text3
        })
        // self.props.form.setFieldsValue({ 'provinceCity': text1 + text2 + text3 });
      } else {
        self.setState({
          contact_province_id: first[selectedIndex[0]].value,
          contact_city_id: second[selectedIndex[1]].value,
          contact_region_id: third[selectedIndex[2]] ? third[selectedIndex[2]].value : '',
          provinceCity1: text1 + text2 + text3
        })
        // self.props.form.setFieldsValue({ 'provinceCity1': text1 + text2 + text3 });
      }
    });
    picker.on('picker.change', function (index, selectedIndex) {
      // console.log(1111)
      if (index === 0) {
        self.firstChange(index, selectedIndex);
      } else if (index === 1) {
        self.secondChange(index, selectedIndex);
      }
    })

    // nameEl.addEventListener('click', function () {
    //   picker.show();
    // });

  }

  creatList(obj, list) {
    obj.forEach(function (item, index, arr) {
      var temp = new Object();
      temp.text = item.name;
      temp.value = item.id;
      list.push(temp);
    })
  }
  firstChange(index, selectedIndex) {
    var self = this;
    second = [];
    third = [];
    checked[0] = selectedIndex;
    // var firstCity = city[selectedIndex];
    // console.log(firstCity)
    // if (firstCity.hasOwnProperty('sub')) {
    //   self.creatList(firstCity.sub, second);

    //   var secondCity = city[selectedIndex].sub[0]
    //   if (secondCity.hasOwnProperty('sub')) {
    //     self.creatList(secondCity.sub, third);
    //   } else {
    //     third = [{ text: '', value: 0 }];
    //     checked[2] = 0;
    //   }
    // } else {
    //   second = [{ text: '', value: 0 }];
    //   third = [{ text: '', value: 0 }];
    //   checked[1] = 0;
    //   checked[2] = 0;
    // }

    var firstCity = first;
    // console.log(first);
    var pid = first[selectedIndex].value;
    self.provice(pid, 1, second, 2);

    picker.refillColumn(1, second);
    picker.refillColumn(2, third);
    picker.scrollColumn(1, 0)
    picker.scrollColumn(2, 0)
  }
  secondChange(index, selectedIndex) {
    var self = this;
    third = [];
    checked[1] = selectedIndex;
    var first_index = checked[0];


    var pid = second[selectedIndex].value;
    self.provice(pid, 3, third, 4);
  }
  pickAdressShow = (type) => {
    this.setState({
      areaType: type
    })
    // console.log(picker);
    picker.show();
  }
  handleSubmit = (e) => {
    e.preventDefault();
    let self = this;
    const token = localStorage.getItem('token');
    // console.log(self.state.province_id)
    self.props.form.validateFields((err, values) => {
      let rex = self.regx(values);
      if (!rex) {

      } else {
        // const params = {
        //   realname: values.realname,
        //   age: values.age,
        //   sex:values.sex,
        //   adress:values.adress
        // }
        self.props.queryUpdate({
          params: {
            ...values,
            province_id: self.state.province_id,
            region_id: self.state.region_id,
            city_id: self.state.city_id,
            // contact_province_id: self.state.contact_province_id,
            // contact_region_id: self.state.contact_region_id,
            // contact_city_id: self.state.contact_city_id,
            // avatar: self.state.avatar,
            token: token
          },
          func: function () {
            message.success('编辑成功!', 1.5, function () {
              self.context.router.push(`/1/app/kmy`);
            });
          }
        })
        // self.props.queryUser({ ...params });
        //this.props.saveUser({ id: '131341313431', user: '蛮王' })
      }
    });
  };
  regx = (item) => {
    let self = this;
    // if (!self.state.avatar) {
    //   message.error('请上传头像');
    //   self.messageConfig();
    //   return false
    // }
    if (!item.realname || item.realname == 'undefined') {
      message.error('请填写姓名');
      self.messageConfig();
      return false
    }
    if (!item.age || item.age == 'undefined') {
      message.error('请填写年龄');
      self.messageConfig();
      return false
    }

    if (!item.id_card || item.id_card == 'undefined') {
      message.error('请填写身份证');
      self.messageConfig();
      return false
    }

    if (!item.qualification || item.qualification == 'undefined') {
      message.error('请填写学历');
      self.messageConfig();
      return false
    }
    // console.log(self.state.param)
    if (!self.state.province_id) {
      message.error('请选择城市');
      self.messageConfig();
      return false
    }
    if (!item.address || item.address == 'undefined') {
      message.error('请填写具体地址');
      self.messageConfig();
      return false
    }

    if (!item.contact_realname || item.contact_realname == 'undefined') {
      message.error('请填写紧急联系人名字');
      self.messageConfig();
      return false
    }
    if (!item.contact_mobile || item.contact_mobile == 'undefined') {
      message.error('请填写紧急联系人联系电话');
      self.messageConfig();
      return false
    }


    return true
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { Statistics, kData, province } = this.props;
    // let vehicleData = data || [];
    // console.log(province);
    // console.log(this.props);
    return (
      <div className={Style.wrap}>
        <div className={Style.headWrap}>
          <div className={Style.navTitle}>
            <span className={Style.arrow} onClick={this.returnFun}><Icon type="left" /></span>
            编辑
          </div>
        </div>
        <div className={Style.conWrap}>
          <Form className="login-form">
            <div className={Style.conItem}>

              <FormItem label='姓名:' {...formItemLayout}>
                {getFieldDecorator('realname', {
                  initialValue: kData && kData.realname || '',
                })(
                  <Input autoComplete="realname" size="" />
                  )}
              </FormItem>
              <FormItem label='年龄:' {...formItemLayout}>
                {getFieldDecorator('age', {
                  initialValue: kData && kData.age || '',
                })(
                  <Input autoComplete="age" />
                  )}
              </FormItem>
              <FormItem label='性别:' {...formItemLayout}>
                {getFieldDecorator('sex', {
                  initialValue: kData && kData.age || '',
                })(
                  <Radio.Group >
                    <Radio value={1}>男</Radio>
                    <Radio value={2}>女</Radio>
                  </Radio.Group>
                  )}
              </FormItem>
              <FormItem label='学历:' {...formItemLayout}>
                {getFieldDecorator('qualification', {
                  initialValue: kData && kData.qualification || '',
                })(
                  <Input autoComplete="qualification" />
                  )}
              </FormItem>
              <FormItem label='所在地址:' {...formItemLayout}>

                <Input placeholder="请选择所在城市" value={this.state.provinceCity} ref='provinceCity' autoComplete="provinceCity" onFocus={this.pickAdressShow.bind(this, 1)} id='citybtn' />


              </FormItem>
              <FormItem label='详细地址' {...formItemLayout}>
                {getFieldDecorator('address', {
                  initialValue: kData && kData.address || ''
                })(
                  <Input placeholder="请输入现居地址" autoComplete="address" />
                  )}
              </FormItem>
              <FormItem label='户籍地:' {...formItemLayout} className="editSelect">
                {getFieldDecorator('household_id', {
                  initialValue: kData && kData.household_id || '',
                })(
                  <Select className='editSelect'>
                    {
                      province.map(function (item, i) {
                        return <Option value={item.id}>{item.name}</Option>
                      })
                    }
                  </Select>
                  )}

              </FormItem>
              <FormItem label='身份证:' {...formItemLayout}>
                {getFieldDecorator('id_card', {
                  initialValue: kData && kData.id_card || '',
                })(
                  <Input autoComplete="id_card" />
                  )}
              </FormItem>
            </div>
            <div className={Style.conItem + ' ' + Style.mt10}>
              <h3>紧急联系人</h3>
              <FormItem
                label="姓名"
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                {getFieldDecorator('contact_realname', {
                  initialValue: kData && kData.contact_realname || '',
                })(
                  <Input value='' />
                  )}
              </FormItem>

              <FormItem
                label="联系电话"
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                className={Style.itemfoot}
              >
                {getFieldDecorator('contact_mobile', {
                  initialValue: kData && kData.contact_mobile || '',
                })(
                  <Input value='' />
                  )}
              </FormItem>
            </div>
            <div className={Style.conbtn + ' ' + Style.mt10}>
              <Form.Item>
                <Button type="primary" htmlType="submit" className="login-form-button" onClick={this.handleSubmit}>
                  提交
                </Button>
              </Form.Item>
            </div>
          </Form>
        </div>

      </div>
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  // console.log(state)
  return {
    kData: state.kmodel.kData,
    province: state.myHome.province
  }
}

function dispatchToProps(dispatch) {
  return {
    e_bikeInfo(payload, params) {
      dispatch({
        type: 'kmodel/e_bikeInfo',
        payload
      })
    },
    queryCity(payload, params) {
      dispatch({
        type: 'myHome/queryCity',
        payload
      })
    },
    queryRegion(payload, params) {
      dispatch({
        type: 'myHome/queryRegion',
        payload
      })
    },
    queryProvince(payload, params) {
      dispatch({
        type: 'myHome/queryProvince',
        payload
      })
    },
    queryUpdate(payload, params) {
      dispatch({
        type: 'kmodel/queryUpdate',
        payload
      })
    }
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
